﻿using System;
using System.Collections.Generic;
using System.Text;
using jade.core.behaviours;
using MarketSimulator.Utils.Attributes;
using jade.lang.acl;
using MarketSimulator.Utils.Communication;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace MarketSimulator.Agents.Behaviors
{
    /// <summary>
    /// Buyer Behavior
    /// </summary>
    public class BuyerBehavior : CyclicBehaviour
    {
        public BuyerAttributes Attributes;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="attributes"></param>
        public BuyerBehavior(BuyerAttributes attributes) 
            : base(attributes.JadeAgent) 
        {
            Attributes = attributes;
        }

        public override void action()
        {
            ACLMessage message = null;
            MessageTemplate pattern = MessageTemplate.MatchConversationId(Messages.CONVERSATION_ASK_OFFER);
            message = myAgent.receive(pattern);

            if (message != null)
            {
                string pInfo = GetProductOffer(message.getContent());
                Attributes.WriteMessage("{0} asked for \"{1}\". My offer is {2}.", message.getSender().getLocalName(),
                    message.getContent(), pInfo);

                //Send message and required info
                ACLMessage reply = new ACLMessage();
                reply.addReceiver(message.getSender());
                reply.setConversationId(Messages.CONVERSATION_SAY_OFFER);
                reply.setContent(pInfo);
                myAgent.send(reply);
            }
            else
            {
                block();
            }
        }

        #region Private Methods

        /// <summary>
        /// Get Offer for Product
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private string GetProductOffer(string productName)
        {
            foreach (var p in Attributes.ShoppingList)
            {
                if (p.Name.ToLower().Equals(productName.ToLower()))
                {
                    return string.Format(Messages.PRODUCT_INFO_FORMAT, p.UnitCost, p.Quantity);
                }
            }
            return Messages.NOT_AVAILABLE;
        }

        #endregion
    }
}
